import { _decorator } from 'cc';
import { IEntity } from '../Levels';
import { EntityManager } from './EntityManager';
import EventManager from '../Runtime/EventManager';
import DataManager from '../Runtime/DataManager';
import { DIRECTION_ENUM, ENTITY_STATE_ENUM, EVENT_ENUM } from '../Enums';
const { ccclass, property } = _decorator;



@ccclass('EnemyManager')
export class EnemyManager extends EntityManager {
    async init(params:IEntity) {
        super.init(params)
        EventManager.Instance.on(EVENT_ENUM.PLAYER_BORN, this.onChangeDirection, this)
        EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onChangeDirection, this)
        EventManager.Instance.on(EVENT_ENUM.ATTACK_ENEMY, this.onDead, this)

        this.onChangeDirection(true)
    }


    onChangeDirection(isInit: boolean = false) {
        if (!DataManager.Instance.player || this.state === ENTITY_STATE_ENUM.DEATH) {
            return;
        }
        //拿到player的坐标
        const { x: playerX, y: playerY } = DataManager.Instance.player
        const disX = Math.abs(this.x - playerX)
        const disY = Math.abs(this.y - playerY)

        if (disX === disY && !isInit) {
            return;
        }

        if (playerX >= this.x && playerY <= this.y) { //在第一象限内
            this.direction = disY > disX ? DIRECTION_ENUM.TOP : DIRECTION_ENUM.RIGHT
        } else if (playerX <= this.x && playerY <= this.y) { //在第二象限内
            this.direction = disY > disX ? DIRECTION_ENUM.TOP : DIRECTION_ENUM.LEFT
        } else if (playerX <= this.x && playerY >= this.y) { //在第三象限内
            this.direction = disY > disX ? DIRECTION_ENUM.BOTTOM : DIRECTION_ENUM.LEFT
        } else if (playerX >= this.x && playerY >= this.y) { //在第四象限内
            this.direction = disY > disX ? DIRECTION_ENUM.BOTTOM : DIRECTION_ENUM.RIGHT
        }

    }

    /**敌人死亡 */
    onDead(id: string) {
        if (this.state === ENTITY_STATE_ENUM.DEATH) {
            return;
        }
        if (this.id === id) {
            this.state = ENTITY_STATE_ENUM.DEATH
        }
    }


    onDestroy() {
        super.onDestroy()
        EventManager.Instance.off(EVENT_ENUM.PLAYER_BORN, this.onChangeDirection)
        EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onChangeDirection)
        EventManager.Instance.off(EVENT_ENUM.ATTACK_ENEMY, this.onDead)
    }


}


